const crypto = require('crypto');
const axios = require('axios');
const dao = require('../dao/dao');
const mchNo = 2025078549;   // 商户号
const currency = 'usd';     // 币种
const key = 'A4r3C2fi5veB5tHstLEB317B7Y9aaHS7';  // 商户密钥
const apiUrl = 'https://www.wiwiusonepay.com/api/transfer/create'; // 提现接口

const queryUrl = 'https://www.wiwiusonepay.com/api/transfer/query'; // 查询提现接口

let orderCounter = 0;

// 开始提现
async function startWithdraw(data, ip) {
    const amount = parseInt(data.amount);
    const playerId = data.playerId;
    const cashTag = data.cashTag;
    const mchOrderNo = generateOrderId();    // 商户订单号
    const wayCode = data.redeemType;            // 提现方式

    const notifyUrl = "http://8.138.47.15:10000/withdrawNotify";

    const timestamp = Date.now();

    // 构建参数列表
    const params = {
        amount: amount * 100,  // 按分提交
        clientIp: ip,
        currency: currency,
        mchNo: mchNo,
        mchOrderNo: mchOrderNo,
        notifyUrl: notifyUrl,
        signType: "MD5",
        timestamp: timestamp,
        wayCode: wayCode,
        wayParam: {
            cashtag: "$" + data.cashTag
        }
    };

    // 生成签名
    const signStr = getSignStr(params, key);
    const sign = getSign(signStr, params.signType);
    params.sign = sign;
    try {
        const response = await axios.post(apiUrl, params, {
            headers: { 'Content-Type': 'application/json' }
        });

        if (response.data.msg === 'SUCCESS') {
            let ret = await dao.insertWithdrawalOrder_WiwiPay(playerId, params, response.data.data, mchNo, cashTag);
            if (ret.respCode === "SUCCESS") {
                response.data.playerCoin = ret.updatedCoin;
                return response.data;
            }else{
                return false;
            }

        } else {
            return false;
        }
    } catch (error) {
        console.error('提现请求错误:', error.message);
        if (error.response) {
            console.error('接口返回状态码:', error.response.status);
            console.error('接口返回数据:', error.response.data);
        }
        return false;
    }
}

// 生成订单号
function generateOrderId() {
    const date = new Date();
    const dateStr = date.getFullYear().toString() +
        String(date.getMonth() + 1).padStart(2, '0') +
        String(date.getDate()).padStart(2, '0') +
        String(date.getHours()).padStart(2, '0') +
        String(date.getMinutes()).padStart(2, '0') +
        String(date.getSeconds()).padStart(2, '0');

    // 自增序列，防止同一秒内重复
    orderCounter = (orderCounter + 1) % 100000; // 5 位流水号
    const counterStr = String(orderCounter).padStart(5, '0');

    return dateStr + counterStr;
}

// 生成签名字符串
function getSignStr(params, key) {
    const sorted = sortValueRecursively(params);
    const entries = Object.entries(sorted)
        .filter(([k]) => k.toLowerCase() !== 'sign')
        .map(([k, v]) => [k, typeof v === 'object' ? JSON.stringify(v) : v])
        .sort(([a], [b]) => a.localeCompare(b));
    const queryString = entries.map(([k, v]) => `${k}=${v}`).join('&');
    return `${queryString}&key=${key}`;
}

// 计算签名
function getSign(signStr, signType) {
    let hash;
    switch (signType.toUpperCase()) {
        case 'MD5':
            hash = crypto.createHash('md5').update(signStr).digest('hex');
            break;
        case 'SHA1':
            hash = crypto.createHash('sha1').update(signStr).digest('hex');
            break;
        case 'SHA256':
            hash = crypto.createHash('sha256').update(signStr).digest('hex');
            break;
        default:
            throw new Error(`Unsupported sign type: ${signType}`);
    }
    return hash.toUpperCase();
}

// 对象递归排序
function sortValueRecursively(value) {
    if (Array.isArray(value)) {
        return value.map(item => sortValueRecursively(item));
    } else if (value && typeof value === 'object') {
        return Object.fromEntries(
            Object.entries(value)
                .map(([k, v]) => [k, sortValueRecursively(v)])
                .sort(([ak], [bk]) => ak.localeCompare(bk))
        );
    }
    return value;
}


async function getOrderStatus(order) {
    let mchNo = order.mchNo;
    let mchOrderNo = order.order_id;
    let timestamp = Date.now();
    let transferOrderNo = order.transfer_order_no;
    let params = {
        "mchNo": mchNo,
        "mchOrderNo": mchOrderNo,
        "signType": "MD5",
        "timestamp": timestamp,
        "transferOrderNo": transferOrderNo
    }
    const signStr = getSignStr(params, key);
    const sign = getSign(signStr, params.signType);
    params.sign = sign;
    try {
        const response = await axios.post(queryUrl, params, {
            headers: { 'Content-Type': 'application/json' }
        });

        if (response.data.msg === 'SUCCESS') {
            await dao.updateWithdrawalOrder_WiwiPay(mchOrderNo, response.data.data);
        } else {
            return false;
        }
    } catch (error) {
        console.error('提现请求错误:', error.message);
        if (error.response) {
            console.error('接口返回状态码:', error.response.status);
            console.error('接口返回数据:', error.response.data);
        }
        return false;
    }
}

module.exports = {
    startWithdraw,
    getOrderStatus
};
